import { _decorator, Component, instantiate, Label, Node, Prefab, tween, Vec3,Vec2, CCString } from 'cc';
import { BallController } from './BallController';
import { MEANING_OF_LIFE } from './Define';
const { ccclass, property } = _decorator;

@ccclass('CardController')
export class CardController extends Component {
	@property(BallController)
    public ballControler: BallController | null = null

    @property(Prefab)
    public pricePrefab: Prefab | null = null;

    public prizeArr: string[] =[]
    
    private _prizePos: Vec3 = new Vec3();

	start() {
        this.prizeArr = this.getRandomElements(MEANING_OF_LIFE,6)
		this.ballControler.node.on('gameOver', this.onCardTween, this)
	}

    getRandomElements<T>(arr: T[], count: number): T[] {
      // 复制原数组以避免修改原始数据
      const tempArr = [...arr]
      const result: T[] = []

      // 确保请求的元素数量不超过数组长度
      if (count > arr.length) {
        console.warn('Requested more elements than available in the array')
        return arr // 返回整个数组作为备选
      }

      // 随机选择元素
      while (result.length < count) {
        const randomIndex = Math.floor(Math.random() * tempArr.length)
        result.push(tempArr.splice(randomIndex, 1)[0])
      }

      return result
    }

	onCardTween(cardNode: Node) {
        
		const tweenCard = tween(cardNode)
			.to(0.5, { position: new Vec3(0, 590, 0) }, { easing: 'backOut' })
            .call(() => {
                this._prizePos = cardNode.position;

                this.showPrize(cardNode.name);
                cardNode.active = false;
            },this);
        
        tweenCard.start();
	}

    showPrize(cardName:string) {
        const cardPos = this._prizePos;
        let priceNode = instantiate(this.pricePrefab);
        priceNode.setParent(this.node.parent);
        priceNode.setPosition(cardPos);
        const index = parseInt(cardName.split("-")[1], 10)|0;
        priceNode.getComponent(Label).string = this.prizeArr? this.prizeArr[index]:"人生赢家";
    }

	protected onDestroy(): void {
		this.ballControler.node.off('gameOver', this.onCardTween, this)
	}

}


